import { Spin, Input, Button } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import type { ExternalTagGroup, ExternalItemTag } from '@/services/contact-types'
import './AddTag.module.less'

export interface TagGroupWithQywx extends ExternalTagGroup {
  wxid: string
  corpId: string
}

export default function AddTagModal(props: {
  adding: TagGroupWithQywx | null
  onFinish: (tag?: ExternalItemTag) => void
}) {
  const { adding, onFinish } = props

  return <EditModal
    styleName="add-tag"
    title="新增标签"
    open={!!adding}
    closable={false}
    onCancel={() => onFinish()}
  >
    {adding ? <AddTag group={adding} onFinish={onFinish} /> : null}
  </EditModal>
}

function AddTag(props: { group: TagGroupWithQywx; onFinish: (tag?: ExternalItemTag) => void }) {
  const { group, onFinish } = props
  const [name, setName] = useState('')
  const [tips, setTips] = useState('')
  const [saving, setSaving] = useState(false)

  const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value)
    setTips('')
  }, [])

  const save = useCallback(async () => {
    const formattedName = name.trim()
    if (!formattedName) return void setTips('请填写标签名称')
    if (group.tags.find(t => t.name === formattedName)) return void setTips('已有同名标签')
    setSaving(true)

    const res = await services.externals.tags.createTag(group.wxid, group.corpId, name)
    if (res.success) {
      onFinish(res.data)
    } else {
      setSaving(false)
      setTips(`标签创建失败：${res.error}`)
    }
  }, [group, name, onFinish])

  return <Spin spinning={saving} tip="保存中...">
    <main>
      <Input placeholder="输入标签名称" value={name} onChange={onChange} autoFocus />
      {tips ? <div styleName="tips">{tips}</div> : null}
    </main>
    <footer>
      <Button onClick={() => onFinish()}>取消</Button>
      <Button type="primary" onClick={save}>
        保存
      </Button>
    </footer>
  </Spin>
}
